#-*-coding:utf-8-*-
# 时间:2019/8/29
# 作者:zfh
import requests, os
import re
import logging
from requests_toolbelt import MultipartEncoder
import requests

m = MultipartEncoder(fields={'field0': 'value', 'field1': 'value'})
# 打印日志
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("my.log")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)

logger.addHandler(handler)
logger.addHandler(console)
# logger.debug("This is a debug log.")
# logger.info("This is a info log.")
# logger.warning("This is a warning log.")
# logger.error("This is a error log.")
# logger.critical("This is a critical log.")
# 初始化网页
initial_url = "http://192.168.17.247:9998"


def send_code():
    '''
    发送验证码
    :return:
    '''
    # 发送短信验证的接口
    api = '/api/ShortMessage/SendPassword/pic'
    # 发送短信验证接口的参数
    m = MultipartEncoder(
        fields={'PhoneNo': '18576444110', 'skey': 'd30f1831874a8a127fc6ae5f30401f3f'})
    # params = {"PhoneNo":(None,"18689487780",'multipart/form-data'),"skey":(None,"2bbd67ba45dff851b34c9e6ed42d1625",'multipart/form-data')}
    # 头信息
    # headers = {"content-type": "application/json;charset=UTF-8"}
    try:
        # 获取发送结果
        code_text = requests.post(initial_url+api, data=m, headers={'Content-Type': m.content_type})
        # print(code_text.text)
        print(code_text.request.body)
        # 使用正则表达式匹配到验证码
        rule = re.compile('"VerCode":"(.+?)"')
        res = rule.findall(code_text.text)
        logger.info("获取验证码成功")
        logger.info('获取验证码接口：----------耗时：%.4f' % code_text.elapsed.total_seconds())
        logger.info(code_text.json()['msg'])
        return res[0]
    except:
        logger.error("获取验证码失败")
        return False


def login_and_get_token(pwd):
    '''
    登录并获取token
    :return:
    '''
    # 获取token接口
    api = '/token'
    # 接口参数
    header = {"grant_type": "1", "username": "18576444110", "password": '%s'%pwd }
    # # 头信息
    # headers = {"content-type": "application/json;charset=UTF-8"}
    try:
        # 获取发送结果
        token_text = requests.post(initial_url+api, params=header)
        # 使用正则表达式匹配到token
        rule = re.compile('"access_token":"(.+?)"')
        res = rule.findall(token_text.text)
        logger.info("获取token成功")
        logger.info('获取token接口：----------耗时：%.4f' % token_text.elapsed.total_seconds())    # 返回结果
        return res[0]
    except:
        logger.error("获取token失败")
        return False


def friend_list(token):
    '''
    好友列表
    :return:
    '''
    api = '/api/Invitation/List'
    # 接口参数
    params = {"pageIndex": 1, "pageSize": 10 }
    # 头信息
    headers = {"Authorization": "%s" % token}
    try:
        # 获取发送结果
        token_text = requests.post(initial_url+api, params=params, headers=headers)
        # 使用正则表达式匹配到count
        rule = re.compile('"count":(.+?),')
        res = rule.findall(token_text.text)
        if res[0] == '0':
            logger.info("获取好友列表成功")
            logger.info('获取好友列表接口：----------耗时：%.4f' % token_text.elapsed.total_seconds())
            return True
        else:
            return False
    except:
        logger.error("获取好友列表失败")
        return False


def get_free_course(token):
    '''
    获取免费课程
    /api/Course/GetFreeCourses
    :param token:
    :return:
    '''
    api = '/api/Course/GetFreeCourses'
    # 接口参数
    params = {"pageIndex": 1, "pageSize": 10 }
    # 头信息
    headers = {"Authorization": "%s" % token}
    try:
        # 获取发送结果
        token_text = requests.post(initial_url+api, params=params, headers=headers)
        # 使用正则表达式匹配到count
        rule = re.compile(r'"result":(.+?),')
        res = rule.findall(token_text.text)
        # print(token_text.text)
        # 返回结果
        if res[0] == 'true':
            logger.info("获取免费课程成功")
            logger.info('免费课程接口：----------耗时：%.4f' % token_text.elapsed.total_seconds())
            return True
        else:
            return False
    except:
        logger.error("获取免费课程失败")
        return False


def user_account_info(token):
    '''
    获取用户账户信息
    /api/UserAccountinfoManage/List
    :param token:
    :return:
    '''
    api = '/api/UserAccountinfoManage/List'
    # 接口参数
    # params = {"pageIndex": 1, "pageSize": 10 }
    # 头信息
    headers = {"Authorization": "%s" % token}
    try:
        # 获取发送结果
        token_text = requests.post(initial_url+api, headers=headers)
        # 使用正则表达式匹配到count
        rule = re.compile(r'"result":(.+?),')
        res = rule.findall(token_text.text)
        # print(token_text.text)
        # 返回结果
        if res[0] == 'true':
            logger.info("获取用户账户信息成功")
            logger.info('用户账户信息接口：----------耗时：%.4f' % token_text.elapsed.total_seconds())
            return True
        else:
            return False
    except:
        logger.error("获取用户账户信息失败")
        return False


def lottery(token):
    '''
    抽奖接口
    /api/lottery/lottery_confirm
    :param token:
    :return:
    '''
    api = '/api/lottery/lottery_confirm'
    # 接口参数
    # params = {"pageIndex": 1, "pageSize": 10 }
    # 头信息
    headers = {"Authorization": "%s" % token}
    try:
        # 获取发送结果
        token_text = requests.post(initial_url+api, headers=headers)
        # 使用正则表达式匹配到count
        rule = re.compile(r'"result":(.+?),')
        res = rule.findall(token_text.text)
        t = token_text.json()['data']['id']
        # 返回结果
        if res[0] == 'true':
            logger.info("抽奖成功")
            logger.info('抽奖接口：----------耗时：%.4f' % token_text.elapsed.total_seconds())
            return True
        else:
            return False
    except:
        logger.error("抽奖失败")
        return False

if __name__ == '__main__':
    if not os.path.exists('user_info'):
        f = open('user_info', 'w')
        f.close()
    # 判断是否需要写入token，默认为1（不需要写入）
    logger.info("***********-----------****************")
    logger.info("***********开始接口测试****************")
    logger.info("***********-----------****************")
    token_flag = 1
    # 打开文件
    with open(r"user_info", "r") as f:
        # 获取token
        old_token = f.read()
        logger.info("获取token：------%s------"%old_token)
        pg = get_free_course(old_token)
        if pg:
            logger.info("token可用")
            # 继续调用接口，进行接口测试
            friend_list(old_token)
            user_account_info(old_token)
            lottery(old_token)
            token_flag = 1
            logger.info("-----------***********----------------")
            logger.info("***********接口测试结束****************")
            logger.info("-----------***********----------------")
        else:
            logger.info("token已失效，重新获取token并退出测试")
            token_flag = 0
    # if token_flag == 0:
    #     code = send_code()
    #     new_token = str(login_and_get_token(code))
    #     # 写入token到user_info中
    #     with open(r"user_info", "w") as f:
    #         f.write(new_token)
    #     logger.info("token获取成功，请重新开始测试")
